import { Input, List, Modal } from 'antd';
import styled from 'styled-components';
import { TableOutlined, PlusOutlined, MinusOutlined, ExclamationOutlined, EditOutlined } from '@ant-design/icons';
import type { SearchProps } from 'antd/es/input/Search';
import { confirm } from '@tauri-apps/plugin-dialog';

const { Search } = Input;

import { createTable, dropTable, getTables } from '@/services/database';
import { useEffect, useState } from 'react';
import { ListItem, Button, CreateTableForm } from '@/components';
import { ConnectorDatabaseType, ConnectorDataSource } from '@/services';
// import { setCurrent } from '@/store/viewer/menu';

export const TableList = (props: {
    current: string | null,
    databaseType: ConnectorDatabaseType,
    dataSource: ConnectorDataSource,
    onClick: (item: any) => Promise<any>
}) => {
    // const dispatch = useDispatch();

    const [isModalOpen, setIsModalOpen] = useState(false);

    const [tables, setTables] = useState<Array<any>>([]);

    const [loading, setLoading] = useState<boolean>(false);

    const [filter, setFilter] = useState<string>('');

    const refresh = (dataSource: ConnectorDataSource) => {
        if (!dataSource) return;

        setTables([]);
        setLoading(true);
        getTables(dataSource).then((res) => {
            console.log(res);
            setTables(res);
            setLoading(false);
        }).catch((err) => {
            console.log(err);
            setLoading(false);
        });
    };
    useEffect(() => {
        refresh(props.dataSource);
    }, [props.databaseType, props.dataSource]);

    return (
        <Container>
            <FilterContainer>
                <Search placeholder="Filter" allowClear={true} onChange={(event) => {
                    setFilter(event.target.value);
                }} onSearch={(value) => {
                    setFilter(value);
                }} />
            </FilterContainer>
            <List
                style={{
                    width: '100%',
                    flex: 1,
                    overflow: 'auto'
                }}
                loading={loading}
                itemLayout="horizontal"
                dataSource={tables.filter((item) => !filter || filter == '' || item.name.toLowerCase().indexOf(filter.toLowerCase()) >= 0)}
                renderItem={(item, index) => (
                    <ListItem
                        key={index}
                        height={40}
                        reverseFill={true}
                        icon={<Button
                            active={props.current === item.name}
                            width={25}
                            icon={<TableOutlined />}
                        ></Button>}
                        title={item.name}
                        active={props.current === item.name}
                        onClick={async () => {
                            await props.onClick(item);
                        }}></ListItem>
                )}
            />
            <TableAdminContainer>
                <Button
                    width={30}
                    icon={<PlusOutlined />}
                    onClick={async () => {
                        //弹出添加对话框
                        setIsModalOpen(true);
                    }}
                ></Button>
                <Button
                    width={30}
                    icon={<MinusOutlined />}
                    disabled={props.current == null}
                    onClick={async () => {
                        //删除表
                        const confirmed2 = await confirm(`确定要删除${props.current}表吗?`, { title: '删除表', kind: 'warning' });

                        try {
                            if (!confirmed2) {
                                return;
                            }
                            let res = await dropTable(props.dataSource, props.current);
                            if (res) {
                                refresh(props.dataSource);
                            } else {

                            }
                        } catch (error) {
                            console.log(error);
                        }
                    }}
                ></Button>
                <Button
                    width={30}
                    icon={<EditOutlined />}
                    disabled={props.current == null}
                    onClick={async () => {
                        // dispatch(setCurrent('structure'));
                    }}
                ></Button>
                <Button
                    width={30}
                    icon={<ExclamationOutlined />}
                    disabled={props.current == null}
                    onClick={async () => {
                        // dispatch(setCurrent('tableinfor'));
                    }}
                ></Button>
            </TableAdminContainer>
            <Modal open={isModalOpen} footer={false} onOk={() => {
                setIsModalOpen(false);
            }} onCancel={() => {
                setIsModalOpen(false);
            }}>
                <CreateTableForm layoutType={'Form'}
                    databaseType={props.databaseType}
                    onSave={async (values) => {
                        //创建数据源并保存
                        try {
                            let res = await createTable(props.dataSource, values);
                            if (res) {
                                refresh(props.dataSource);
                            } else {

                            }
                            setIsModalOpen(false);
                        } catch (error) {
                            console.log(error);
                        }
                    }}></CreateTableForm>
            </Modal>
        </Container>
    );
};

export default TableList;

const Container = styled.div`
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: #F1EBE7;
`;

const FilterContainer = styled.div`
    height: 40px;
    width: 100%;
    display: flex;
    align-items: center;
    padding:0 2px;
`;

const TableAdminContainer = styled.div`
    height: 36px;
    width: 100%;
    padding:0 6px;
    background-color: #DDDDDD;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
    gap: 10px;
`;
